import os
import random
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from mydjango.settings import Django_URL, Vue_URL, UPLOAD_ROOT

from PIL import Image, ImageDraw, ImageFont

import io

from .utils import chack_token, make_token, r0, make_password
from .baidu_audio import generate_audio

from .models import User

# 自定义图片验证码
#定义验证码类
class MyCode(View):
    #定义随机颜色方法
    def get_random_color(self):
        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)
        return (R,G,B)

	# 定义随机验证码
    def get(self,request):
        uuid = request.GET.get("uuid")
        if not uuid:
            return HttpResponse({"code": 999, "msg": "参数不齐"})
        # 定义画布大小 宽，高
        img_size = (120,50)
        #定义画笔 颜色种类,画布，背景颜色
        image = Image.new("RGB",img_size,'white')
        #定义画笔对象 图片对象,颜色类型
        draw = ImageDraw.Draw(image,'RGB')
        #定义随机字符
        source = '0123456789asdfghjkl'
        #定义四个字符
        #定义好容器，用来接收随机字符串
        code_str = ''
        for i in range(4):
            #获取随机颜色 字体颜色
            text_color = self.get_random_color()
            #获取随机字符串
            tmp_num = random.randrange(len(source))
            #获取字符集
            random_str = source[tmp_num]
            #将随机生成的字符串添加到容器中
            code_str += random_str
            #将字符画到画布上 坐标，字符串，字符串颜色，字体
            #导入系统真实字体,字号
            my_font = ImageFont.truetype("c:\\windows\\Fonts\\arial.ttf",30)
            draw.text((10+30*i,20)
            ,random_str,text_color,my_font)
        #使用io获取一个缓存区
        buf = io.BytesIO()
        #将图片保存到缓存区
        image.save(buf,'png')
        
        # 存入redis种，设置两分钟超时
        r0.set(uuid, code_str)
        r0.expire(uuid, 60*2)
        
        # 写入MP3文件
        print(123)
        generate_audio(code_str)
        print(321)
        # 设置过期时间
        #将随机码存储到session中
        request.session.set_expiry(60)
        request.session["code"] = code_str
        
        session_key = request.session.session_key
        print("sessionkey:", session_key)

        #第二个参数声明头部信息
        return HttpResponse(buf.getvalue(),'image/png')


# 注册接口
class Register(APIView):

    def post(self, request):
        # 获取参数
        username = request.data.get("username")
        password = request.data.get("password")
        password2 = request.data.get("password2")
        code = request.data.get("code")
        uuid = request.data.get("uuid")
        
        # 判断参数完整性
        if not all([username, password, password2, code]):
            return Response({"code": 999, "msg": "参数不齐"})
        # 判断两次密码是否一致
        if password != password2:
            return Response({"code": 999, "msg": "两次密码不一致"})
        # 获取session和redis的验证码
        session_code = request.session.get("code")
        redis_code = r0.get(uuid)
        # 判断验证码
        if code !=session_code or code != redis_code:
            return Response({"code": 999, "msg": "验证码错误"})
        
        # username设置的唯一索引，报错返回用户名重复
        try:
            user_obj = User(username=username, password=make_password(password))
            user_obj.save()
        except Exception as e:
            print(e)
            return Response({"code": 999, "msg": "用户名重复"})
        else:
            return Response({"code": 200, "msg": "注册成功"})


#登录接口
class UserLogin(APIView):
    

    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")
        print(username, password)
        if not all([username, password]):
            return Response({"code": 999, "msg": "参数不齐"})
        user_obj = User.objects.filter(username=username)
        print(user_obj.first())
        if not user_obj:
            return Response({"code": 999, "msg": "该用户不存在"})
        user_obj = user_obj.first()
        if user_obj.password == make_password(password):
            request.session.set_expiry(3600*24)
            request.session["uid"] = user_obj.id
            return Response({"code": 200,"msg": "登录成功", "uid": user_obj.id})
        return Response({"code": 999, "msg": "密码错误"})
    
    
    
# def stream(request):
#     resp = HttpResponse(open(os.path.join(UPLOAD_ROOT, '','003.mp3'),'rb'), content_type="audio/mpeg")
#     resp['Content-length'] = os.path.getsize(os.path.join(UPLOAD_ROOT, '','003.mp3'))
#     resp['Content-Disposition'] = 'filename=test.mp3'
    
#     return resp



    